package com.maoslv.controller;

import com.maoslv.aop.LogAnnotation;
import com.maoslv.dto.Result;
import com.maoslv.service.user.UserService;
import com.maoslv.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Random;

@RestController
@Scope("request")
@EnableAsync
public class EmailController {
    @Autowired
    JavaMailSender mailSender;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    UserService userService;

    @PostMapping("/email")
    @LogAnnotation(operator = "获取邮箱验证码")
    public Result getCode(@RequestBody Map<String,String> map) throws UnsupportedEncodingException, AddressException {

        String username = map.get("username");
        String email = map.get("email");
        if (username == null || username.equals("")) {
            return Result.fail("用户名不能为空");
        }
        if (email == null || email.equals("")) {
            return Result.fail("邮箱不能为空");
        }

        Random random = new Random();
        String num = "";
        for (int i = 0;i < 4;i++) {
            num += random.nextInt(10);
        }
        String verCode = num;
        userService.sendEmail(email, "您本次的验证码是", "尊敬的用户,您好:\n"
                + "\n本次请求的邮件验证码为:" + verCode + ",本验证码 5 分钟内效，请及时输入。（请勿泄露此验证码）\n"
                + "\n如非本人操作，请忽略该邮件。\n(这是一封通过自动发送的邮件，请不要直接回复）");
        redisUtil.set(username + "-email",num,300);
        return Result.succ("发送成功",null);
    }
}
